<!-- 发展历程,该功能进入的时候需要将所有的地铁路线都清除，离开的时候再添加回来，使用该功能的时候无法使用图层管理控件 -->
<template>
  <div class="center-wrapper">
    <!-- 地铁线路 -->
    <div id="subLine-controller">
      <div class="title-bg"><i class="iconfont icon-luxuan"></i>地铁线路</div>
      <div class="item-wrapper">
        <div class="item" v-for="item in subLineData" @click.stop="handleItemClick(item)">
          <div class="box" :style="{ borderColor: item.color, backgroundColor: item.color }"></div>
          <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
        </div>
      </div>
    </div>
    <!-- 发展历程 -->
    <div class="active-panel">
      <div class="header">
        <strong>发展历程</strong>
        <div class="controler">
          <i class="iconfont icon-zanting" @click="pause"></i>
          <i class="iconfont icon-bofang" @click="play"></i>
          <i class="iconfont icon-a-zhongboshuaxin" @click="replay"></i>
        </div>
      </div>
      <div class="content">
        <div class="slider">
          <a-slider v-if="resPaths.length!==0" v-model:value="currentTime" :marks="marks" :step="0.5" :min="0" :max="max"></a-slider>
        </div>
        <div class="message" v-if="message.length">{{ message }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from 'vue';
import { getLine } from '@/api/line.js';
import { useLineData } from '@/store/index.js';

import { line_history } from '@/store/staticData';

import { flattenPositions } from '@/cesiumTools/core';
import { flyToDefaultView, renderAll, removeByCacheData, removeAll, changeDisplayBillBoard, } from '@/cesiumTools/controller/effectController';
// import linkSeriesData from 'echarts/types/src/data/helper/linkSeriesData.js';

import {
  controlAll,
  chooseLine,
} from '@/cesiumTools/controller/lineController.js';

const lineData = useLineData();
let viewer

// 定义地铁线路数据
const subLineData = ref([]);

// 定义a-slider所需的数据
let resPaths = []
let curPaths = []
let dataEnts = {}
const currentTime = ref(0)
const marks = ref({})
const max = ref(0)
const message = ref('')

// 点击对应线路，视角跳转，并重新渲染该线路，id要不一样，路线坐标使用callbackProperty
// dataEnts类型 {
//   lineEnts:[],
//   stationEnts:[],
//   billboards:[]
// }
const handleItemClick = (item) => {
  // 站线数据解构, id为1, paths为构成的坐标点
  const { id, paths } = item;
  console.log(paths)
  const positions = flattenPositions(paths)
  console.log(positions.slice(0, 2))

  pause()

  const target = line_history.find((n) => n.id === id);
  console.log(target)
  if (target) {
    pause()
    currentTime.value = 0;

    // 渲染站点站线,不走内部缓存,要获取返回值，在外部进行管理
    dataEnts = renderAll(viewer, [item], false)

    // 渲染时间slider
    // 解构发展历程数据
    const { history } = target;

    max.value = (history.length - 1) * 10;

    let res = {};
    history.forEach((item, index) => {
      res[index * 10] = {
        style: {
          color: "#fff",
          fontSize: 10,
        },
        label: item.timePoint,
        message: item.message,
      };
    });
    console.log(res)

    // 给播放控件赋值，并给路径数据赋值
    marks.value = res;

    resPaths = positions;
    curPaths = positions.slice(0, 2);

    play()
    
    // 飞行到默认点
    flyToDefaultView(viewer)

    console.log(dataEnts)
    // 找到路线的实体，并给其坐标重新赋值
    const entity = dataEnts.lineEnts[0]
    // 给播放控件赋值，并给路径数据赋值
    entity.polyline.positions = new Cesium.CallbackProperty(() => Cesium.Cartesian3.fromDegreesArray(curPaths), false)
  }
}

onMounted(() => {
  // store仓库获取viewer 
  viewer = lineData.Viewer

  // 站线数据全部保存到store中了, 所以不需要再用get向服务器请求再获取数据
  subLineData.value = lineData.allData

  // 获取每个站线的名称
  const lineNames = lineData.allData.map((item => item.name))
  console.log(lineNames)

  // // 调用pinia中定义的方法, 将站线全部隐藏, lineNames为所有站线的数组, false为不显示状态
  // lineData.displayLine(lineNames, false)
  // console.log(lineData)
  handleAllLineChecked()

  // 暂时禁用全局管理，unMount的时候打开
  lineData.disableController(true)
});

onBeforeUnmount(() => {
  pause()
  // 清除已经有的数据以及实体
  removeByCacheData(viewer, dataEnts)
  dataEnts = null
  // 全局管理恢复，图层控制
  lineData.disableController(false)
  // 将站点站线全部展示
  const lineNames = lineData.allData.map(item => item.name)
  lineData.displayLine(lineNames, true)
})

//控制全部显示或者隐藏
const handleAllLineChecked = () => {
  //为true时显示所有线路和popup，为false时隐藏所有线路和popup
  controlAll(false, subLineData);
  let names = [];
  subLineData.value.forEach(line => {
    const { stationsList } = line;
    //console.log(stationsList)
    stationsList.forEach(station => {
      names.push(station.name);
    });
  });
  //console.log(names);
  //changeDisplayBillBoard(names, false);
};

let isAnimate
const pause = () => {
  isAnimate = false
};

let myRequestID = null;
const play = () => {
  cancelAnimationFrame(myRequestID)
  const animate = () => {
    if (isAnimate) {
      currentTime.value += 0.1;
      const rate = currentTime.value / max.value;
      let index = Math.ceil(rate * resPaths.length);
      // 我们的坐标两个为一组，不为双数的话，就加一
      if (index % 2 !== 0) {
        index = index + 1;
      }
      // 如果是最后一个坐标，就返回
      if (index >= resPaths.length - 1) {
        curPaths = resPaths;
        isAnimate = false
        return;
      }

      curPaths = resPaths.slice(0, index);
      requestAnimationFrame(animate)
      myRequestID=requestAnimationFrame(animate)
    }
  }
  isAnimate = true
  animate()
}

const replay = () => {
    pause();
    currentTime.value = 0;
    curPaths = resPaths.slice(0, 2);
    play();
}

const removeCurrentEnts = () => {
  if(dataEnts.length > 0) {
    viewer.entities.remove(dataEnts.lineEnts[0])
  }else {
    return
  }
}

// 监听当前进度
// 1.找到当前进度在marks当中的下标
// 2.通过下标,找message
watch(currentTime, (val) => {
    let targetIndex = null;
    const markKeys = Object.keys(marks.value).map((n) => Number(n));
    const markValues = Object.values(marks.value);
    markKeys.forEach((m, index) => {
        // 判断val是否在值区间
        if (index > 0 && val <= m && val > markKeys[index - 1]) {
            targetIndex = index;
        }

        if (val <= m && index === 0) {
            targetIndex = index;
        }
    });
    if (targetIndex) {
        const result = markValues[targetIndex];
        message.value = result.message;
    } else {
        message.value = "";
    }
});
</script>

<style scoped lang="scss">
@import url('http://at.alicdn.com/t/c/font_4778950_jht8cywqcuq.css');

.center-wrapper {
  display: flex;
  gap: 10px;
  position: absolute;
  bottom: 90px;
  left: 29%;
  width: 800px;
  height: 280px;
  z-index: 1060;

  /* 地铁线路列表 */
  #subLine-controller {
    width: 180px;
    background-color: rgba(0, 0, 0, 0.3);
    border: 1px solid #ab7818;
    display: flex;
    flex-direction: column;

    .title-bg {
      line-height: 30px;
      margin-left: 10px;
      background: rgb(255, 255, 255);
      background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
      background-clip: text; //保证-webkit-background-clip不会提示错误
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
  }

  /* 发展历程 */
  .active-panel {
    border: 1px solid #ab7818;
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    flex: 1;

    .header {
      display: flex;
      justify-content: space-between;
      height: 30px;
      padding: 4px;
      background: rgb(255, 255, 255);
      background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
      background-clip: text;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin-bottom: -0.521vw;
      font-family: "等线Bold";

      strong {
        font-weight: normal;
        margin-right: 10px;
      }

      .controler {
        display: flex;
        align-items: center;
        justify-content: space-around;
        gap: 10px;

        i {
          cursor: pointer;
          pointer-events: all;
          font-size: 20px;

          &:hover {
            background: rgb(255, 255, 255);
            background-image: linear-gradient(180deg, rgba(255, 255, 255, 1) 9%, rgba(211, 156, 50, 1) 57%);
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          }
        }
      }  
    }

    .content {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 100%;

      .slider {
        width: 90%;
        margin: 30px 0px;
        padding: 20px;
        white-space: nowrap;

        a-slider {
          width: 100%;
          padding: 10px;
        }
        
        :deep(.ant-slider) {
          padding: 4px;
        }
      }

      .message {
        background-color: rgba(0, 0, 0, 0.3);
        color: #fff;
        text-align: center;
      }
    }
  } 

    

  .item-wrapper {
    display: flex;
    justify-content: space-around;
    align-content: space-around;
    flex-wrap: wrap;
    flex: 1;
    padding: 12px 4px;
    overflow: hidden;

    .item {
      width: 70px;
      height: 25px;
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      background-color: rgba(255, 255, 255, 0.2);
      border: 1px solid #885f12;
      color: #fff;
      font-size: 0.8vw;
      pointer-events: all;

      &:hover {
        border: 1px solid #d8961a;
        cursor: default;
      }

      span {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 42px;
      }

      .box {
        width: 10px;
        height: 10px;
        border-width: 1px;
        border-style: solid;
        background: transparent;
        user-select: all;
        cursor: pointer;
        transition: all 0.3s linear;
        z-index: 1040;
      }
    }
  }
}
</style>